from syncora_sdk.client import SyncoraClient
from syncora_sdk.schemas.constants.literal import FileType
from syncora_sdk.storage.s3 import S3Uploder
from syncora_sdk.schemas.synthetic import SyntheticDataRequest
from pydantic import ValidationError, HttpUrl
from pathlib import Path
import csv
from syncora_sdk.schemas.dto.SyntheticDataDto import SyntheticDataDto


class SyntheticDataGenerator:
    def __init__(self, client: SyncoraClient):
        self.client = client
        self.s3 = S3Uploder(client)

    def generate(
        self,
        fileUrl: HttpUrl,
        type: FileType,
        numberOfRows: int,
        fileSizeBytes: int,
        sourceFileRows: int,
        targetColumn: str,
    ):
        try:
            paylaod = SyntheticDataRequest(
                fileUrl=fileUrl,
                type=type,
                numberOfRows=numberOfRows,
                fileSizeBytes=fileSizeBytes,
                sourceFileRows=sourceFileRows,
                targetColumn=targetColumn,
            )
        except ValidationError as e:
            raise ValueError(
                f"Invalid parameters for synthetic data generation:\n{e}"
            ) from e
        print(f'generating data...')
        response = self.client.post("/ai/execute", json=paylaod.model_dump(mode="json"))
        return SyntheticDataDto(response).data

    def generate_from_file(
        self, file_path: Path, type: FileType, numberOfRows: int, targetColumn: str
    ):
        file = Path(file_path)
        file_size = file.stat().st_size

        with open(str(file_path), newline="") as csvfile:
            reader = csv.reader(csvfile)
            row_count = sum(1 for _ in reader) - 1

        filename = file.name

        # print(row_count)
        # print(file_size)
        # print(filename)

        urls = self.s3.get_presigned_url(fileName=filename)
        # print("signed url response", urls)
        if urls:
            # print(urls["uploadUrl"])
            # print(urls["publicUrl"])
            self.s3.upload_file(urls["uploadUrl"], file_path=file_path)
            return self.generate(
                fileUrl=urls["publicUrl"],
                type=type,
                numberOfRows=numberOfRows,
                fileSizeBytes=file_size,
                sourceFileRows=row_count,
                targetColumn=targetColumn,
            )
        else:
            raise Exception("Failed to upload file")
